﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zo.Extensions;
using ZoLone.Models.Sys;

namespace ZoLone.Logics.Sys
{
    public class OperationLogLogic:BaseLogic
    {
        /// <summary>
        /// 添加日志记录
        /// </summary>
        /// <param name="adminId">管理员id</param>
        /// <param name="controller">控制器</param>
        /// <param name="action">方法名</param>
        /// <param name="url">网址</param>
        /// <param name="desc">描述</param>
        /// <param name="content">参数内容</param>
        /// <param name="area">域信息</param>
        /// <returns></returns>
        public bool AddLog(HttpContext filterContext, int adminId, string controller, string action,string area)
        {
            if (filterContext==null)
            {
                return false;
            }
            var query = filterContext.Request.QueryString.ToString();
            var ip = filterContext.Connection.RemoteIpAddress.ToString();
            var url = filterContext.Request.Path + query;
            IFormCollection form = null;
            var dictionary = new Dictionary<string, object>();
            if (filterContext.Request.Form != null)
            {
                form = filterContext.Request.Form;

                foreach (var key in form.Keys)
                {
                    dictionary[key] = form[key];
                }
            }
            var data = JsonConvert.SerializeObject(dictionary);

            Sys_OperationLog log = new Sys_OperationLog();
            log.AdminId = adminId;
            log.Controller = controller;
            log.Action = action;
            log.Desc = "";
            log.Content = "";
            log.Ip = ip;
            log.Area = area;
            log.Url = url;

            log.CreateTime = DateTime.UtcNow.GetTimeStamp();
            db.Sys_OperationLog.Add(log);
            var r = db.SaveChanges();
            return  r> 0;            
        }
        /// <summary>
        /// 管理员日志
        /// </summary>
        /// <param name="total">总记录数</param>
        /// <param name="order">排序字段</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="where">条件</param>
        /// <returns></returns>
        public List<Sys_OperationLog> GetData(out int total,Func<Sys_OperationLog, bool> order,
             int pageIndex=0,int pageSize=0,Func<Sys_OperationLog, bool> where=null)
        {
            total =db.Sys_OperationLog.Where(where).Count();
            var result =db.Sys_OperationLog.Where(where).OrderByDescending(order).Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList();
            return result;
        }
    }
}
